package de.uni.leipzig.meddins.server;

import java.io.IOException;

import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpException;
import org.apache.http.HttpServerConnection;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpService;

public class ConnectionThread extends Thread {
	private final HttpService httpservice;
	private final HttpServerConnection conn;

	public ConnectionThread(final HttpService httpservice,
			final HttpServerConnection conn) {
		super();
		this.httpservice = httpservice;
		this.conn = conn;
	}

	public void run() {
		HttpContext context = new BasicHttpContext(null);
		try {
			while (!Thread.interrupted() && this.conn.isOpen()) {
				//TODO hier muss ich noch eine Liste von den connections und deren URIs machen, damit ich das sendAll()
				// realisieren kann. Ich brauche eine Registry, die das macht. Erst dannach darf ich den Request 
				// handlen
				this.httpservice.handleRequest(this.conn, context);
			}
		} catch (ConnectionClosedException ex) {
			System.err.println("Client closed connection");
		} catch (IOException ex) {
			System.err.println("I/O error: " + ex.getMessage());
		} catch (HttpException ex) {
			System.err.println("Unrecoverable HTTP protocol violation: "
					+ ex.getMessage());
		} finally {
			try {
				this.conn.shutdown();
			} catch (IOException ignore) {
			}
		}
	}
	
	public void finalize(){
		try {
			this.conn.shutdown();
		} catch (IOException ignore) {}
	}
}
